// pages/house-keep/index.js
import Config from '../../etc/config'
import util from '../../utils/util'
var app = getApp()
const {
  $Toast
} = require('../../components/dist/base/index');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cate: '../../images/icon/category.png',
    brand: '../../images/icon/brand.png',
    right: '../../images/icon/right.png',
    repair: '../../images/icon/repair.png',
    fruit: [{
      name: '保修期外'
    }, {
      name: '保修期内'
    }],
    isWarranty: 0,
    current: '',
    position: 'left',
    checkItems: [{
      categoryId: '',
      category: '',
      brand: [{
        id: '',
        name: ''
      }]
    }],
    typeId: '',
    addId: '',
    type: '',
    disabled: false,
    index: '',
    fileName: '',
    buyCert: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.data.typeId = options.typeId
    this.setData({
      type: options.type
    })
    if (wx.getStorageSync('userId')) {
      this.getAdImg(options.type)
    } else {
      wx.navigateTo({
        url: '../authorize/index',
      })
    }
    var DATE = util.formatDate(new Date());
    this.setData({
      start: DATE,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (this.data.addId !== '') {
      this.getAddrById()
    }
    this.getAddLength()
    // this.getAdImg(this.data.type)
  },

  // 获取用户地址数量
  getAddLength() {
    let params = {
      userId: wx.getStorageSync('userId'),
    }
    let token = wx.getStorageSync("token");
    Config._post('/useraddress/userAddressIsExistByUserId', token, params).then(res => {
      if (res.data) {
        this.setData({
          msg: '选择收货地址',
          handleWay: 'selectAddress'
        })
      } else {
        this.setData({
          msg: '增加收货地址',
          handleWay: 'addAddress'
        })
      }
    })
  },

  // 获取默认地址和页面广告图
  getAdImg(type) {
    let params = {
      userId: wx.getStorageSync('userId'),
      typeId: type
    }
    let token = wx.getStorageSync("token");
    Config._post('/merServicesType/getImgStrByTypeId', token, params).then(res => {
      if (res.data.userAddress) {
        this.setData({
          addressInfo: res.data.userAddress,
          addId: res.data.userAddress.id
        })
        this.getShop()
      }
      if (res.data.path) {
        this.setData({
          img: res.data.path
        })
      }
    })
  },

  // 选择地址
  selectAddress() {
    wx.navigateTo({
      url: '../address/index?typeId=' + this.data.typeId,
    })
  },

  // 添加地址
  addAddress() {
    wx.navigateTo({
      url: '../add-address/index',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  // 修改地址
  editAddess(e) {
    wx.navigateTo({
      url: '../add-address/index?id=' + e.currentTarget.dataset.id,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  // 根据地址ID获取地址详情
  getAddrById() {
    let params = {
      id: this.data.addId
    }
    let token = wx.getStorageSync("token");
    Config._post('/useraddress/getAddrById', token, params).then(res => {
      this.setData({
        addressInfo: res.data
      })
      this.getShop()
    })
  },

  // 修改会员卡号
  cardChange(e) {
    var cardNumber = 'addressInfo.member'
    this.setData({
      cardNumber: e.detail.value
    })
  },

  // 获取门店信息
  getShop() {
    wx.showLoading({
      title: '加载中',
    })
    let params = {
      merSerTypeId: this.data.typeId,
      addressId: this.data.addId
    }
    let token = wx.getStorageSync("token");
    Config._post('/merServicesType/getMerSerTypeDetail', token, params).then(res => {
      console.log(res)
      if (res.code === 0) {
        if (res.data.label) {
          this.setData({
            label: res.data.cateList
          })
        }
        this.setData({
          shopId: res.data.shopId
        })
        wx.setNavigationBarTitle({
          title: res.data.name
        })
      }
      wx.hideLoading()
    })
  },

  // 跳转分类
  goSelect() {
    if (this.data.shopId) {
      if (this.data.type == '3') {
        wx.navigateTo({
          url: '/pages/cate-brand/index?shopId=' + this.data.shopId + '&typeId=' + this.data.typeId + '&type=' + this.data.type + '&checkItems=' + JSON.stringify(this.data.checkItems) + '&isClick=true',
        })
      } else {
        wx.navigateTo({
          url: '/pages/cate-brand/index?shopId=' + this.data.shopId + '&typeId=' + this.data.typeId + '&type=' + this.data.type + '&checkItems=' + JSON.stringify(this.data.checkItems),
        })
      }
    } else {
      if (this.data.addId == '') {
        $Toast({
          content: '请选择联系人'
        })
      } else {
        $Toast({
          content: '未找到商家'
        })
      }
      return
    }
  },

  // 是否在保修期
  bindChange(e) {
    this.setData({
      isWarranty: e.detail.value
    })
  },
  // handlechange(e) {
  //   this.setData({
  //     isWarranty: e.currentTarget.dataset.index
  //   })
  // },

  // 选中分类的备注
  valueChange(e) {
    let idx = e.target.dataset.index,
      value = e.detail.value,
      id = e.currentTarget.dataset.id
    for (let i = 0; i < this.data.checkItems.length; i++) {
      if (this.data.checkItems[i].brand[idx].brandId == id) {
        var a = i
      }
    }
    var index = "checkItems[" + a + "].brand[" + idx + "].value"
    this.setData({
      [index]: value
    })
  },

  // textarea备注
  valueInput(e) {
    this.setData({
      buyerRemake: e.detail.value
    })
  },

  tagClick(e) {
    this.data.index = e.currentTarget.dataset.index
    this.data.checkItems[0].categoryId = e.currentTarget.dataset.id
    this.data.checkItems[0].category = e.currentTarget.dataset.name
  },

  bindCateChange(e) {
    this.data.checkItems[0].brand[0].id = this.data.label[this.data.index].brandList[e.detail.value].id
    this.data.checkItems[0].brand[0].name = this.data.label[this.data.index].brandList[e.detail.value].name
    this.setData({
      // checkItems: this.data.checkItems,
      index: this.data.index,
      buyerRemake: this.data.label[this.data.index].categorie.name + '-' + this.data.label[this.data.index].brandList[e.detail.value].name
    })
  },

  // 删除选中分类
  tagClickDel(e) {
    // let id = e.currentTarget.dataset.id
    // var checkTags = this.data.checkItems
    // for (let i = 0; i < checkTags.length; i++) {
    //   if (id === checkTags[i].categoryId) {
    //     checkTags.splice(i, 1)
    //     break
    //   } else {
    //     for (let j = 0; j < checkTags[i].brand.length; j++) {
    //       checkTags[i].brand.splice(j, 1)
    //       break
    //     }
    //   }
    // }
    // this.setData({
    //   checkItems: checkTags
    // })
    let checkTages = [{
      categoryId: '',
      category: '',
      brand: [{
        id: '',
        name: ''
      }]
    }]
    this.setData({
      checkItems: checkTages,
      index: ''
    })
  },

  bindDateChange(e) {
    this.setData({
      date: e.detail.value,
    })
  },

  // 下单
  orderSubmit: function(e) {
    this.setData({
      disabled: true
    })
    wx.showLoading({
      // title: '',
    })
    let formId = e.detail.formId
    if (!this.data.checkItems[0].brand[0].id || this.data.buyerRemake == '') {
      $Toast({
        content: '请选择分类'
      });
      this.setData({
        disabled: false
      })
      wx.hideLoading()
      return;
    }
    var buyCert = ''
    for (let i = 0; i < this.data.buyCert.length; i++) {
      if (i === this.data.buyCert.length - 1) {
        buyCert += this.data.buyCert[i].fileName
      } else {
        buyCert += this.data.buyCert[i].fileName + ','
      }
    }
    let params = {
      userId: wx.getStorageSync('userId'),
      merTypeId: this.data.typeId,
      shopId: this.data.shopId,
      addressId: this.data.addId,
      formId: formId,
      bTime: this.data.date ? Date.parse(this.data.date) : '',
      buyCert: buyCert
    }
    let token = wx.getStorageSync("token");
    params.buyerRemake = this.data.buyerRemake === undefined ? '' : this.data.buyerRemake
    params.categoryId = this.data.checkItems[0].categoryId
    params.orderCategory = this.data.checkItems[0].category
    params.brandId = this.data.checkItems[0].brand[0].id
    params.orderBrand = this.data.checkItems[0].brand[0].name
    // params.orderIsWarranty = this.data.isWarranty
    Config._post('/order/submitOrder', token, params).then(res => {
      this.setData({
        disabled: false
      })
      wx.hideLoading()
      wx.reLaunch({
        url: '../success-msg/index',
      })
    })
  },

  // 上传凭证
  upLoad() {
    const that = this
    wx.chooseImage({
      count: 6,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        if (res.tempFiles.length > 6 || that.data.buyCert.length + res.tempFiles.length > 6) {
          $Toast({
            content: '最多可上传6张'
          })
          return false
        } else {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths
          let token = wx.getStorageSync('token')
          wx.showLoading({
            title: '上传中',
          })
          for (let i = 0; i < tempFilePaths.length; i++) {
            wx.uploadFile({
              url: Config.basePath + '/file/upload', // 仅为示例，非真实的接口地址
              filePath: tempFilePaths[i],
              name: 'file',
              formData: {
                access_token: token
              },
              success(res) {
                const data = JSON.parse(res.data)
                let options = {
                  fileName: data.data.bucketName + '-' + data.data.fileName,
                  path: tempFilePaths[i]
                }
                that.data.buyCert.push(options)
                that.setData({
                  buyCert: that.data.buyCert
                })
              },
              fail(res) {
                // console.log('上传失败', res)
              },
              complete(res){
                if (i = tempFilePaths.length - 1) {
                  wx.hideLoading()
                }
              }
            })
          }
        }
      }
    })
  },

  delBuyCert(e) {
    this.data.buyCert.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      buyCert: this.data.buyCert
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      // title: wx.getStorageSync('mallName') + '——' + app.globalData.shareProfile,
      title: app.globalData.shareTitle,
      path: '/pages/repair/index?type=' + this.data.type + '&typeId=' + this.data.typeId,
      imageUrl: this.data.img,
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  }
})